#include <buola/buola.h>
#include "ctorrent.h"

namespace buola { namespace bitdaemon {

CTorrent::CTorrent(libtorrent::torrent_handle pHandle)
    :   mHandle(pHandle)
{
    if(pHandle.has_metadata())
    {
        int lNumFiles=mHandle.get_torrent_info().num_files();
        mPriorities.resize(lNumFiles,1);
    }
}

CTorrent::~CTorrent()
{
}

std::wstring CTorrent::GetStatusString()
{
    using libtorrent::torrent_status;

    torrent_status lStatus=mHandle.status();
    
    switch(lStatus.state)
    {
    case torrent_status::downloading_metadata:
        return L"downloading metadata";
    case torrent_status::queued_for_checking:
        return L"queued for hashing";
    case torrent_status::checking_files:
        return L"hashing";
    case torrent_status::downloading:
        if(lStatus.paused)
            return L"paused";
        else
            return L"downloading";  
    case torrent_status::finished:
    case torrent_status::seeding:
        return L"finished";
    case torrent_status::allocating:
        return L"allocating";
    default:
        return L"unknown";
    }
}

std::wstring CTorrent::GetName()
{
    return utf32(mHandle.name().c_str());
}

void CTorrent::Pause()
{
    mHandle.pause();
}

void CTorrent::Resume()
{
    mHandle.resume();
}

double CTorrent::GetProgress()
{
    libtorrent::torrent_status lStatus=mHandle.status();
    
    return lStatus.progress;
}

size_t CTorrent::GetSize()
{
    return GetInfo().total_size();
}

double CTorrent::GetDLSpeed()
{
    libtorrent::torrent_status lStatus=mHandle.status();
    
    return (double)lStatus.download_payload_rate;
}

double CTorrent::GetULSpeed()
{
    libtorrent::torrent_status lStatus=mHandle.status();
    
    return (double)lStatus.upload_payload_rate;
}

int CTorrent::GetFileCount()
{
    return GetInfo().num_files();
}

std::string CTorrent::GetFileNameAt(int i)
{
    return GetInfo().file_at(i).path.c_str();
}

void CTorrent::SetPriority(int pIndex,int pPriority)
{
    mPriorities[pIndex]=pPriority;
    mHandle.prioritize_files(mPriorities);
}

int CTorrent::GetTrackerCount()
{
    return mHandle.trackers().size();
}

io::CURI CTorrent::GetTrackerURIAt(int i)
{
    return io::uri(mHandle.trackers()[i].url.c_str());
}

void CTorrent::AddTracker(const io::CURI &pURI)
{
    std::vector<libtorrent::announce_entry> lTrackers=mHandle.trackers();
    lTrackers.push_back(pURI.ToString());
    mHandle.replace_trackers(lTrackers);

    mHandle.force_reannounce();
}

/*namespace bitdaemon*/ } /*namespace buola*/ }
